<?php

namespace App\Http\Controllers\Mp;

use App\Models\User;
use App\Utils\Reg;
use App\Utils\Sms;
use Illuminate\Http\Request;

/**
 * Class CodeController
 * @package App\Http\Controllers\Mp
 * @author zjw
 */
class CodeController extends BaseController
{

    public function index(){
        return 'test';
    }

    /**
     * @param Request $request
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function store(Request $request)
    {
        $phone = $request->get("phone", '');
        if (!Reg::checkPhone($phone)) {
            return $this->fail('请输入正确的手机号');
        }
        if (\Cache::has("code:limit:" . $phone)) {
            return $this->fail('发送过于频繁');
        }
        $user = User::where("phone", $phone)->first();
        if (!$user) {
            return $this->fail('该手机用户不存在，如有问题，请联系你的学校');
        }
        if($phone === '13788888888'){
            $code = 123456;
        }else {
            $code = random_int(100000, 999999);
        }
        \Cache::put('login_code:' . $phone, $code, now()->addMinute(30));
        \Cache::put("code:limit:" . $phone, 1, now()->addSecond(60));
        $sms = new Sms();
        $res = $sms->send($phone, [
            'template' => '231310',
            'data' => [
                $code, 30
            ]
        ]);
        if ($res) {
            return [];
        } else {
            return $this->fail('发送失败，请稍后尝试');
        }

    }
}
